package com.iepacj.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;

import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;

/**
 * Created by iEpac on 16/4/9.
 */
public class ZookeeperCreateApiAsync implements Watcher{


    private static CountDownLatch cdl = new CountDownLatch(1);


    public static void main(String[] args) throws Exception {

        String connStr = "localhost:2181";

        ZooKeeper zk = new ZooKeeper(connStr, 3000, new ZookeeperCreateApiAsync());

        cdl.await();

        ArrayList<ACL> acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;


        /**
         * rc: 服务端响应码, 从这个响应码中可以知道api调用的结果.
         *      0: ok调用成功
         *      -4: 连接已断开
         *      -110: 指定节点已存在
         *      -112: 会话过期
         *
         * path: API调用时传入的path参数
         * ctx:  API调用时传入的ctx参数
         * name: 实际在服务端创建的节点名
         *
         */
        zk.create("/zk-test-async-", "".getBytes(), acl, CreateMode.EPHEMERAL, new AsyncCallback.StringCallback() {
            @Override
            public void processResult(int rc, String path, Object ctx, String name) {
                System.out.println("创建节点异步回调: " + path + ", rc = " + rc + ", ctx = " + ctx + ", name = " + name);
            }
        }, "object ctx");

        zk.create("/zk-test-async-", "".getBytes(), acl, CreateMode.EPHEMERAL_SEQUENTIAL, new AsyncCallback.StringCallback() {
            @Override
            public void processResult(int rc, String path, Object ctx, String name) {
                System.out.println("创建节点异步回调: " + path + ", rc = " + rc + ", ctx = " + ctx + ", name = " + name);
            }
        }, "object ctx");


        Thread.sleep(Integer.MAX_VALUE);
    }


    @Override
    public void process(WatchedEvent event) {

        System.out.println("收到watcher事件: " + event);

        if (Event.KeeperState.SyncConnected == event.getState()) {
            System.out.println("连接建立...");
            cdl.countDown();
        } else if (Event.EventType.NodeChildrenChanged == event.getType()) {
            System.out.println("子节点发生变更::" + event.getPath());
        }


    }
}







